package com.zoo.curator;

import com.jz.util.AttributeSupport;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.io.IOException;

/**
 * Created by Administrator on 2015/10/30.
 */
abstract public class AbstractLeaderSelectorClient extends LeaderSelectorListenerAdapter implements Closeable {
    public static final Logger LOGGER = LoggerFactory.getLogger(AbstractLeaderSelectorClient.class);
    protected final String name;
    protected final LeaderSelector leaderSelector;
    protected AbstractCurator curator;

    public AbstractLeaderSelectorClient(final AbstractCurator curator, String name) {
        this.curator = curator;
        this.name = name;
        leaderSelector = new LeaderSelector(curator.client, AttributeSupport.MAIN_LEADER, this);
        leaderSelector.autoRequeue();
        leaderSelector.start();
    }

    public void close() throws IOException {
        leaderSelector.close();
    }

    public boolean isLeader() {
        return leaderSelector.hasLeadership();
    }

    public void release() {
        leaderSelector.interruptLeadership();
    }

    public void take() {
        leaderSelector.requeue();
    }

    /**
     * 供外部调用的释放方法,执行后释放LEADER权限,停止CHILD
     */
    public void releaseWithProcess() {
        leaderSelector.interruptLeadership();
        curator.killProcess(null);
    }

}